// Package ioc
// Created by GoLand
// @User: lenora
// @Date: 2024/8/27
// @Time: 17:28

package ioc

import (
	intrv1 "camp/microbook/api/proto/gen/interactive"
	"camp/microbook/interactive/service"
	"camp/microbook/internal/client"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func InitInteractiveClient(svc service.InteractiveService) intrv1.InteractiveServiceClient {
	var cfg struct {
		Addr   string
		Secure bool
	}

	err := viper.UnmarshalKey("grpc.client.intr", &cfg)
	if err != nil {
		panic(err)
	}
	opts := make([]grpc.DialOption, 0)
	if !cfg.Secure {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}

	cc, err := grpc.Dial(cfg.Addr, opts...)
	if err != nil {
		panic(err)
	}
	remote := intrv1.NewInteractiveServiceClient(cc)
	local := client.NewInteractiveAdapter(svc)
	res := client.NewInteractiveClient(remote, local)
	viper.OnConfigChange(func(in fsnotify.Event) {
		threshold := viper.GetInt32("grpc.client.intr.threshold")
		res.UpdateThreshold(threshold)
	})
	return res
}
